<template>
  <view class="w-full">
    <van-cell-group inset>
      <van-cell title="所在楼层" use-label-slot>
        <view slot="label" class="flex items-center h-10 location-class">
          <view
            :class="{
              'w-90%': true,
              'c-text-14': true,
              'c-black': data.address,
            }"
            @click="
              () => {
                data.show = true;
              }
            "
          >
            {{ data.address ? data.address : '请选择栋单元层' }}
          </view>
          <view class="w-10% text-align-center">
            <i class="i-ic:sharp-clear w-4 h-4" @click="clearAddress"></i>
          </view>
        </view>
      </van-cell>
    </van-cell-group>

    <van-popup :show="data.show" position="bottom">
      <van-cascader v-if="data.show" :active-color="'#ffc300'" :field-names="{ text: 'name', value: 'id' }" :value="data.cascaderValue" title="请选择所在地区" :options="data.cascaderOptions" @close="cascaderClose" @change="cascaderChange" @finish="cascaderFinish" />
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import Tools from '@/utils/tools';
import userRequest from '@/request/userRequest';
import useAppStore from '@/store/modules/app';
import HomeRequest from '@/request/homeRequest';

interface IProps {
  isGetUserAddress: boolean;
}

interface IData {
  show: boolean;
  cascaderValue: string;
  address: string;
  cascaderData: IBuildingTreeRes[];
  cascaderOptions: IBuildingTreeRes[];
  cascaderSelectedOptions: IBuildingTreeRes[];
  addressType: number;
}

type EmitEvents = {
  (event: 'returnData', payload: { item: IBuildingTreeRes[]; isUpload: boolean }): void; //返回数据
  (event: 'clearData'): void; //返回数据
};

const props = defineProps<IProps>();

const emits = defineEmits<EmitEvents>();

const store = useAppStore();

const { beeperId } = store.$state;

const data = reactive<IData>({
  show: false,
  cascaderValue: '',
  cascaderData: [],
  cascaderOptions: [],
  cascaderSelectedOptions: [],
  addressType: 4,
  address: '',
});

onMounted(() => {
  fetchFloorTreeInformation(beeperId);
  if (props.isGetUserAddress) {
    getBeeperAddress();
  }
});

const cascaderClose = () => {
  data.show = false;
};

const cascaderFinish = (e: any) => {
  const { selectedOptions, value } = e.detail;
  data.cascaderSelectedOptions = selectedOptions;
  data.cascaderValue = value;
  data.address = selectedOptions.map((option: IBuildingTreeRes) => option.name).join('/');
  emits('returnData', { item: data.cascaderSelectedOptions, isUpload: true });
  data.show = false;
};

// 获得单元层信息
const fetchFloorTreeInformation = (beeperId: number) => {
  userRequest.BuildingTree({ beeperId }).then((res) => {
    data.cascaderData = res.data;
    data.cascaderOptions = Tools.deEmptyChildrenCascader(res.data).map((item) => {
      if (data.addressType === 4) {
        return item;
      }
      return { ...item, children: [] };
    });
  });
};

// 地区选择器选中事件
const cascaderChange = (e: any) => {
  const { tabIndex, selectedOptions, value } = e.detail;
  const insertData = Tools.findPathDFS<IBuildingTreeRes>(data.cascaderData, e.detail.value);
  if (!insertData) return;
  const index = data.cascaderData.findIndex((item) => item.id === insertData.id);
  data.cascaderValue = value;
  data.cascaderSelectedOptions = selectedOptions;
  if (tabIndex === 0) {
    data.cascaderOptions = Tools.deEmptyChildrenCascader(data.cascaderData).map((item) => {
      return { ...item, children: [] };
    });
    data.cascaderOptions[index].children = insertData.children;
  }
};

//获取当前用户呼叫器所在楼栋层
const getBeeperAddress = () => {
  HomeRequest.GetBeeperAddress({ beeperId: beeperId, hasLoading: true }).then((res) => {
    if (res.status === 0) {
      const { buildId, buildName, unitId, unitName, floorId, floorName, houseNumberId, houseNumber } = res.data;
      const selectedOptions = [
        {
          id: buildId,
          name: buildName,
        },
        {
          id: unitId,
          name: unitName,
        },
        {
          id: floorId,
          name: floorName,
        },
        {
          id: houseNumberId,
          name: houseNumber,
        },
      ].map((item) => ({
        ...item, // 保留原有的 id 和 name
        parentId: 0,
        levels: 0,
        children: [],
      }));
      emits('returnData', { item: selectedOptions, isUpload: false });
      data.address = buildName + '/' + unitName + '/' + floorName + '/' + houseNumber;
      if (houseNumberId) {
        data.cascaderValue = String(houseNumberId);
      } else if (floorId) {
        data.cascaderValue = String(floorId);
      } else if (unitId) {
        data.cascaderValue = String(unitId);
      } else if (buildId) {
        data.cascaderValue = String(buildId);
      }
    }
  });
};

//清空地址
const clearAddress = () => {
  emits('clearData');
  data.cascaderValue = '';
  data.cascaderSelectedOptions = [];
  data.address = '';
};

defineExpose({
  clearAddress,
});
</script>

<style lang="scss" scoped>
.location-class {
  padding: 10rpx;
  border: 1px solid #ddd;
  border-radius: 16rpx;
  box-sizing: border-box;
}
</style>
